from django.core.management.base import BaseCommand
from order.audit_worker import start_audit_worker, stop_audit_worker
import signal
import sys

class Command(BaseCommand):
    help = '启动评论审核工作器'
    
    def add_arguments(self, parser):
        parser.add_argument(
            '--daemon',
            action='store_true',
            help='以守护进程模式运行',
        )
    
    def handle(self, *args, **options):
        """启动审核工作器"""
        self.stdout.write(
            self.style.SUCCESS('正在启动评论审核工作器...')
        )
        
        # 注册信号处理器
        def signal_handler(signum, frame):
            self.stdout.write(
                self.style.WARNING('收到停止信号，正在关闭审核工作器...')
            )
            stop_audit_worker()
            sys.exit(0)
        
        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)
        
        try:
            # 启动审核工作器
            start_audit_worker()
            
            self.stdout.write(
                self.style.SUCCESS('评论审核工作器已启动')
            )
            
            # 保持运行
            if not options['daemon']:
                self.stdout.write('按 Ctrl+C 停止工作器')
                while True:
                    import time
                    time.sleep(1)
                    
        except KeyboardInterrupt:
            self.stdout.write(
                self.style.WARNING('正在停止审核工作器...')
            )
            stop_audit_worker()
            self.stdout.write(
                self.style.SUCCESS('审核工作器已停止')
            )
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(f'启动审核工作器失败: {str(e)}')
            )
            sys.exit(1) 